<script setup>
import { getTradeListAPI, getAddressByIdAPI,updateTradeAPI,payAPI,receiveAPI } from '@/api/Trade.js';
import { useUserStore } from "@/stores/user";
import { ref, computed } from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import { formatDate } from '@/utils/format.js';

// 获取用户ID
const userStore = useUserStore();
const userId = userStore.UserId;
// 是否显示收件信息弹窗
const showAddressDialog = ref(false);

// 存储交易列表
const tradeList = ref([]);
// 收件人信息
const addressInfo = ref({});

const showPayDialog = ref(false);
const selectedPayMethod = ref('balance'); // 默认选择余额支付
const payPassword = ref('');
const currentOrderId = ref(null);
const orderPrice = ref(0);




// 初始化时获取交易列表
const getTradeList = async () => {
  const res = await getTradeListAPI(userId);
  tradeList.value = res.data.data;
  console.log(tradeList.value);
};

// 页面加载时获取交易数据
getTradeList();

// 选中的状态，默认选中“待付款”
const activeStatus = ref("0");

// 根据当前选中状态进行过滤
const filteredTradeList = computed(() =>
    tradeList.value.filter(item => item.status === parseInt(activeStatus.value))
);

// 点击支付时触发，打开支付弹窗
const payOrder = async (orderId, price) => {
  currentOrderId.value = orderId;
  orderPrice.value = price;
  showPayDialog.value = true; // 显示支付弹窗
};

// 确认支付的逻辑
const confirmPayment = async () => {
  try {
    const response = await payAPI(currentOrderId.value, payPassword.value, orderPrice.value, userId);
    if (response.data.code === 200) {
      ElMessage.success("支付成功！");
      showPayDialog.value = false;
      //重置数据
      payPassword.value = '';

      await getTradeList(); // 重新获取交易列表
    } else {
      ElMessage.error("支付失败，请重试！");
    }
  } catch (error) {
    ElMessage.error("支付出错！");
  }
};
// 取消订单
const cancelOrder = async (orderId) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
        '确定要取消此订单吗？',
        '取消确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    // 如果用户确认，调用API取消订单
    const response = await updateTradeAPI(orderId,2);
    if (response.data.code === 200) {
      ElMessage.success("取消订单成功！");
      await getTradeList(); // 重新获取交易列表
    } else {
      ElMessage.error("取消订单失败！");
    }
  } catch (error) {
    // 用户取消或发生错误时的处理
    ElMessage.info("取消操作已取消");
  }
};

const showAddressInfo = async (addressId) => {
  const res = await getAddressByIdAPI(addressId);
  addressInfo.value = res.data.data;
  showAddressDialog.value = true;
};
const cancelPay = () => {
  showPayDialog.value = false;
  payPassword.value = '';
};
// 确认收货函数，带确认弹窗
const confirmReceive = async (orderId, goodsId, userId, nums) => {
  try {
    // 显示确认框
    await ElMessageBox.confirm(
        '确定要确认收货吗？',
        '确认收货',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    // 用户确认后调用API
    const response = await receiveAPI(orderId, goodsId, userId, nums);
    if (response.data.code === 200) {
      ElMessage.success("确认收货成功！");
      await getTradeList(); // 重新获取交易列表，更新状态
    } else {
      ElMessage.error("确认收货失败，请重试！");
    }
  } catch (error) {
    // 用户取消或发生错误时的处理
    ElMessage.info("操作已取消");
  }
};
// 状态标签
const statusLabels = ["待付款", "已支付", "已取消", "已完成","已发货"];
</script>

<template>
  <!-- 状态切换选项卡 -->
  <el-tabs v-model="activeStatus" @tab-click="() => {}">
    <el-tab-pane
        v-for="(label, index) in statusLabels"
        :key="index"
        :label="label"
        :name="index.toString()"
    ></el-tab-pane>
  </el-tabs>

  <!-- 交易列表 -->
  <div class="trade-list">
    <el-card
        v-for="trade in filteredTradeList"
        :key="trade.id"
        shadow="hover"
        class="trade-item"
    >
      <el-table v-if="trade" :data="[trade]" style="margin-top: 40px">
        <el-table-column label="商品图片" width="100">
          <template #default="scope">
            <img :src="scope.row.image" alt="商品图片" class="product-image" />
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称" width="100" />
        <el-table-column prop="orderNumber" label="订单编号" width="160" />
<!--        订单类型-->
        <el-table-column label="订单类型" width="100">
          <template #default="scope">
            {{ trade.type === 2 ? '二手订单' : '新品订单' }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价/元" width="80" />

        <el-table-column prop="nums" label="数量" width="60" />
        <el-table-column label="总价/元" width="100">
          <template #default="scope">
            <span style="color: blue">{{ (scope.row.price * scope.row.nums).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="收件信息" width="150">
          <template #default="scope">
            <el-button
                type="primary"
                size="small"
                @click="showAddressInfo(scope.row.mailAddressId)"
            >
              查看地址
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                  v-if="scope.row.status === 0"
                  type="success"
                  size="small"
                  @click="payOrder(scope.row.id, (scope.row.price * scope.row.nums).toFixed(2))"
              >
                去支付
              </el-button>
              <el-button
                  v-if="scope.row.status === 0 || scope.row.status === 1"
                  type="danger"
                  size="small"
                  @click="cancelOrder(scope.row.id)"
              >
                取消订单
              </el-button>
              <el-button
                  v-if="scope.row.status === 4"
              type="primary"
              size="small"
              @click="confirmReceive(scope.row.id, scope.row.goodsId, userId, scope.row.nums)"
              >
              确认收货
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="showAddressDialog" title="收件人信息" width="40%">
      <div style="font-size: 18px">
        <p>收件人：{{ addressInfo.addressee }}</p>
        <p>联系电话：{{ addressInfo.addresseePhone }}</p>
        <p>收货地址：{{ addressInfo.address }}</p>
      </div>
    </el-dialog>

    <el-dialog v-model="showPayDialog" title="选择支付方式" width="30%">
      <div>
        <el-radio-group v-model="selectedPayMethod">
          <el-radio-button label="balance">余额支付</el-radio-button>
          <el-radio-button label="wechat" disabled>微信支付</el-radio-button>
          <el-radio-button label="alipay" disabled>支付宝支付</el-radio-button>
        </el-radio-group>
      </div>
      <div style="margin-top: 15px;">
        <el-input
            type="password"
            v-model="payPassword"
            placeholder="请输入支付密码"
            show-password
        />
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button  @click="cancelPay">取消</el-button>
    <el-button type="primary" @click="confirmPayment">确认支付</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<style scoped>
.trade-list {
  margin-left: -330%;
  margin-top: 30%;
}

.trade-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

</style>
